package com.ljdemo.lrecorder.activity

import android.Manifest
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.animation.AlphaAnimation
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.ljdemo.lrecorder.R
import com.ljdemo.lrecorder.model.Timer
import com.ljdemo.lrecorder.model.Timer.TimeChangeListener
import com.ljdemo.lrecorder.service.ScreenRecordService
import com.ljdemo.lrecorder.utils.AlertUtil
import com.ljdemo.lrecorder.utils.AppUtil
import com.ljdemo.lrecorder.utils.TimeUtil

class ScreenRecordActivity : AppCompatActivity() {

    private lateinit var timeT:TextView
    private lateinit var img:ImageView
    private lateinit var audioSwitch:Switch

    // 静态对象
    companion object{
        private const val permission_request_code=1002
        private const val RECORD_REQUEST_CODE = 100
        private var DISPLAY_WIDTH = 720
        private var DISPLAY_HEIGHT = 1280
        private var mScreenDensity = 0
        private val TAG=ScreenRecordActivity::class.java.name.toString()
    }

    // 管理屏幕捕捉和录制的框架
    private var mProjectionManager: MediaProjectionManager? = null
    // 录制标志位
    private var isRecording=false
    private lateinit var timer:Timer
    private var perAlertIsShow=false // 权限被拒绝弹窗是否显示

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_screen_record)

        initView()
        initTimer()
        checkPermission()
    }

    override fun onBackPressed() {
        /** 在onBackPressed中实现比较稳定 */
        if (ScreenRecordService.isRecording){
            // 将当前activity放入后台，而非销毁
            moveTaskToBack(true)
            return
        }
        super.onBackPressed()
    }

    private fun initView(){
        timeT=findViewById(R.id.sr_tv)
        img=findViewById(R.id.sr_img)
        img.setOnClickListener(object : OnClickListener{
            @RequiresApi(Build.VERSION_CODES.O)
            override fun onClick(p0: View?) {

                //防止连续点击
                if (AppUtil.isFastClick()){
                    return
                }

                if (isRecording){
                    // 结束录制
                    stopRecord()
                }else{

                    // 检查权限
                    if (checkPermission()){
                        // 开始录屏
                        startRecord()
                    }

                }
            }
        })
        audioSwitch=findViewById(R.id.sr_audio_switch)
    }

    private fun initTimer(){
        timer=Timer()
        timer.setTimeChangeListener(object : TimeChangeListener{
            override fun timeChange(time: Int) {
                timeT.text=TimeUtil.formatMiss(time)
            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun startRecord(){
        // 开始录屏
        mProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        //开启录制/投射屏幕权限请求弹窗，请求码为 RECORD_REQUEST_CODE
        startActivityForResult(
            mProjectionManager!!.createScreenCaptureIntent(),
            RECORD_REQUEST_CODE
        )
        // 开始录屏前改变UI
        startUiChange()
    }

    // 开始录屏的UI改变
    private fun startUiChange(){
        isRecording=true
        img.setImageResource(R.mipmap.lujing)
        runAnim()
        // 开始计时
        timer.start()
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    fun stopRecord(){
        // 停止计时
        timer.stop()
        isRecording=false
        img.setImageResource(R.mipmap.kaishi)
        runAnim()

        // 向录屏service发送停止消息
        val service=Intent(this,ScreenRecordService::class.java)
        service.putExtra("type",1)
        startForegroundService(service)
    }

    private fun runAnim(){
        // 过渡动画
        val alphaAnimation = AlphaAnimation(0f,1f)
        alphaAnimation.duration=1000
        alphaAnimation.fillAfter=true
        img.startAnimation(alphaAnimation)
    }

    // 检查权限
    private fun checkPermission():Boolean{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            // 需要申请的权限数组
            val permissions:Array<String> = arrayOf(
                Manifest.permission.RECORD_AUDIO,// 录音权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写文件权限
                Manifest.permission.READ_EXTERNAL_STORAGE,// 读文件权限
                Manifest.permission.FOREGROUND_SERVICE// 前台服务
            )
            for (permission:String in permissions){
                if (ContextCompat.checkSelfPermission(this@ScreenRecordActivity,permission) != PackageManager.PERMISSION_GRANTED){
                    // 发现没有权限
                    // 自动申请
                    ActivityCompat.requestPermissions(this,permissions, permission_request_code)
                    return false
                }
            }
        }
        return true
    }

    // 权限被拒绝提示弹窗
    private fun perAlert(){
        if (perAlertIsShow){
            return
        }
        perAlertIsShow=true
        AlertUtil.alert(this,"没有权限","没有权限录屏功能将无法使用","去开启权限","取消",
            object : DialogInterface.OnClickListener{
                override fun onClick(p0: DialogInterface?, p1: Int) {
                    // 跳转到系统设置该应用的信息页去开启权限
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivityForResult(intent, 200)// 已弃用

                    perAlertIsShow=false
                    p0?.dismiss()
                }
            },
            object : DialogInterface.OnClickListener{
                override fun onClick(p0: DialogInterface?, p1: Int) {
                    perAlertIsShow=false
                    p0?.dismiss()
                }
            })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RECORD_REQUEST_CODE){
            if (resultCode != RESULT_OK){
                AlertUtil.showCenterToast(this,"录屏权限被禁止")
                Log.e(TAG,"录屏权限被禁止")
                return
            }

            //获取屏幕宽度，高度和像素密度
            val displayMetrics=resources.displayMetrics;
            DISPLAY_WIDTH=displayMetrics.widthPixels
            DISPLAY_HEIGHT=displayMetrics.heightPixels
            mScreenDensity=displayMetrics.densityDpi

            val serIntent=Intent(this,ScreenRecordService::class.java)
            serIntent.putExtra("type", 0)
            serIntent.putExtra("code", resultCode)
            serIntent.putExtra("data", data)
            serIntent.putExtra("density", mScreenDensity)
            serIntent.putExtra("width", DISPLAY_WIDTH)
            serIntent.putExtra("height", DISPLAY_HEIGHT)

            // 是否开启声音录制
            val audioIsOn=audioSwitch.isChecked
            serIntent.putExtra("audio",audioIsOn)

            startForegroundService(serIntent)

            // 返回桌面
            val homeIntent = Intent(Intent.ACTION_MAIN)
            homeIntent.addCategory(Intent.CATEGORY_HOME)
            startActivity(homeIntent)
        }else{
//            checkPermission()
        }
    }

    /**
     * 权限请求后回调
     * @param requestCode 请求码
     * @param permissions 请求的权限数组
     * @param grantResults 请求的权限是否同意数组
     */
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        println("-----------")

        // Build.VERSION.SDK_INT为动态获取的sdk版本
        // Build.VERSION_CODES.M为固定值24，即android6.0
        // 判断sdk版本大于等于23，请求码为200
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == permission_request_code) {

            var flag=true
            for (i in permissions.indices) {
                // 判断请求的权限用户是否同意
                // PackageManager.PERMISSION_GRANTED为同意，PackageManager.PERMISSION_DENIED为拒绝
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    flag=false
                }
            }

            if (!flag){
                // 没有权限，弹窗提示
                perAlert()
            }

        }

    }

}